<script setup lang="ts">
import {ref, onUpdated, reactive, onMounted} from 'vue'
import {ElMessage, ElTable} from 'element-plus'
import {carsInfoStore} from '@/stores/cars'
import {ArrowDown} from '@element-plus/icons-vue'
import {getCarsDropDownApi} from '@/api/cars'
import {useSku} from "@/hook/sku";
import {getDetailBannerApi} from '@/api/details/index'
import {useRoute, useRouter} from "vue-router";
//使用skuHook
const skuHook = useSku()
//字典
let skuMap = {}
//当前路由信息
const route = useRoute();
const router = useRouter();

//把数组分成对应等份

function splitArrayIntoEqualParts(arr: any, partsCount: number) {
  if (arr.length % partsCount !== 0) {
    throw new Error('Array length is not divisible by the number of parts');
  }

  const chunkSize = arr.length / partsCount;
  const result = [];

  for (let i = 0; i < arr.length; i += chunkSize) {
    // 注意：这里使用slice会创建新的数组，但它包含的是对原数组中元素的引用
    result.push(arr.slice(i, i + chunkSize));
  }

  return result;
}


let num = ref(1)

//购物车数据
const userCars = carsInfoStore()
const tableData = userCars.carsList
const dropdownStatus = reactive(new Array(userCars.carsList.length).fill(false))


//删除购物车商品
function deleteItemCar(row: object) {
  userCars.removeCarInfo(row.skuId)
}

//获取购物车商品信息下拉框
const skuCars = ref([])

//获取购物车商品信息下拉框
async function getCarsDropDown(index: number) {
  // 遍历并关闭所有其他下拉菜单
  for (let i = 0; i < dropdownStatus.length; i++) {
    if (i !== index) {
      dropdownStatus[i] = false;
    }
  }
  if (!dropdownStatus[index] == true) {
    dropdownStatus[index] = true;
    let res = await getCarsDropDownApi(tableData[index].skuId)
    if (res.msg == '操作成功') {
      skuCars.value = res.result
      //生成字典
      skuMap = skuHook.getValidSku(skuCars.value)
      //初始化sku
      skuHook.initDisable(skuCars.value.specs, skuMap)
    }
  }

}


//修改选项
function changeSku(item: any, val: any, index: number) {
  skuHook.changeSku(item, val, skuCars, skuMap)
  console.log(skuHook.skuIdObj.value)
  userCars.updateCarInfo(skuHook.skuIdObj.value, index)
}


//修改数量
function changeCount(item: any, count: number) {
  userCars.updateCarCount(item.skuId, count)
}

//选中商品
const selectedCars = ref([])

//选中商品(单个)
function checkSelection(selected: boolean, item: any) {
  userCars.selectCarInfo(selected, item.skuId)
  console.log(item)
}

//选中商品(多个)
function checkSelectionAll(selected: boolean) {
  userCars.selectAllCarInfo(selected)
}

//确定按钮
function changeSkuRight(index: number) {
  dropdownStatus[index] = false;
}

//删除已选择
function removeAllCar() {
  let seleArr = userCars.carsList.filter(item => item.selected)
  if (seleArr.length > 0) {
    let ids = seleArr.map((item) => {
      return item.skuId
    })
    userCars.removeSelectCarInfo(ids)
  } else {
    ElMessage.error('请选择要删除的商品')
  }
}

//轮播部分

//首页轮播数据
const swiperData = ref([]);

//获取bannerApi
async function getDetailBanner() {
  let res = await getDetailBannerApi(route.params.id)
  if (res.msg == '操作成功') {
    swiperData.value = res.result
    swiperData.value = splitArrayIntoEqualParts(swiperData.value, 4)
  }
}

//结算
function settlement() {
  router.push('/address')
}

onMounted(() => {
  userCars.getCartList()
  getDetailBanner()
})

</script>

<template>
  <div class="cars">
    <div class="car-heart">
      <div class="car-content">
        <div class="car-table">
          <table>
            <thead>
            <tr>
              <th width="120">
                <el-checkbox type="checkbox" :model-value="userCars.isAll" @change="checkSelectionAll"></el-checkbox>
                <span>全选</span>
              </th>
              <th width="400">商品信息</th>
              <th width="220">单价</th>
              <th width="180">数量</th>
              <th width="180">小计</th>
              <th width="120">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in userCars.carsList" :key="item.index">
              <td>
                <!-- elment-plus的checkbox回调函数（自定义）中存放选中状态（参数形式） 以此用箭头函数返回一个函数获取选中状态和当前行数据 -->
                <el-checkbox type="checkbox" :model-value='item.selected'
                             @change="(selected:boolean)=>checkSelection(selected,item)"></el-checkbox>
              </td> <!-- 全选框可以用checkbox实现 -->
              <td>
                <div class="commodity-info">
                  <div class="commodity-info-img">
                    <img :src="item.picture">
                  </div>
                  <div class="commodity-info-text">
                    <div class="commodity-name">
                      <span>{{ item.name }}</span>
                    </div>
                    <div class="commodity-down">
                      <span @click="getCarsDropDown(index)" class="commodity-down-name-text">
                        {{ item.attrsText }}
                        <el-icon>
                          <ArrowDown></ArrowDown>
                        </el-icon>
                      </span>
                      <Transition name="slide-fade">
                        <div class="commodity-down-content" v-if="dropdownStatus[index]">
                          <div class="commodity-down-item" v-for="(val, key) in skuCars.specs" :key="key">
                            <div class="commodity-down-name">
                              <span>{{ val.name }}</span>
                            </div>
                            <div class="commodity-down-item-list">
                              <div class="cdil-item" v-for="(v, k) in val.values" :key="k"
                                   :class="{active:v.selected, disabled:v.disable}" @click="changeSku(val, v, index)">
                                <img :src="v.picture" v-if="v.picture">
                                <span v-else>{{ v.name }}</span>
                              </div>
                            </div>
                          </div>
                          <div class="commodity-down-bth">
                            <el-button type="primary" size="large" @click="changeSkuRight(index)">确定</el-button>
                          </div>
                        </div>
                      </Transition>
                    </div>
                  </div>
                </div>
              </td>
              <td>{{ item.price }}</td>
              <td>
                <el-input-number v-model="item.count" :min="1" :max="10"
                                 @change="(count:number)=>{changeCount(item,count)}"/>
              </td>
              <td><span class="tb-price">¥{{ item.count * item.price }}</span></td>
              <td class="operation">
                <p>移入收藏夹</p>
                <p class="tb-delete" @click="deleteItemCar(item)">删除</p>
                <p>找相似</p>
              </td> <!-- 操作列可以用按钮或其他元素表示 -->
            </tr>
            <!-- 这里可以添加更多的行数据 -->
            </tbody>
          </table>
          <div class="car-table-btn" style="margin-top: 20px;">
            <div class="left-btn">
              <el-button link @click="removeAllCar">删除已选择</el-button>
            </div>
            <div class="right-btn">
              <div class="right-btn-text">
                <span> 共 {{ userCars.carsList.length }} 件商品，已选择 {{ userCars.selectedCount }} 件，商品合计： </span>
                <span
                    class="right-price">￥{{ userCars.totalPrice }}</span>
              </div>
              <div class="right-btn-btn">
                <el-button type="primary" size="large" @click="settlement">下单结算</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      推荐模块-->
      <div class="recommend">
        <div class="recommend-title">
          <i class="iconfont icon-dingwei"></i>
          <h2>同类商品</h2>
        </div>
        <div class="recommend-content">
          <el-carousel :interval="5000" arrow="always">
            <el-carousel-item v-for="(item,index) in swiperData" :key="index">
              <div class="recommend-list">
                <div class="recommend-item" v-for="swpItem in item" :key="swpItem.id">
                  <div class="recommend-item-image">
                    <img v-lazy-img="swpItem.picture">
                  </div>
                  <div class="recommend-item-info">
                    <span>{{ swpItem.name }}</span>
                  </div>
                  <div class="recommend-item-price">
                    <span>¥{{ swpItem.price }}</span>
                  </div>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cars {
  width: 100%;
  min-height: 46.9rem;
  background-color: #f5f5f5;
  padding: 2.5rem 0;
  box-sizing: border-box;
}

.car-heart {
  width: var(--primary-heart-width);
  margin: 0 auto;
}

.car-colum {
  display: flex;
  align-items: center;
  gap: 0.43rem;
}

.car-img img {
  width: 8.33rem;
  height: 8.33rem;
  object-fit: cover;
}

.car-info-name {
  font-size: 1.33rem;
  color: #333;
  margin-bottom: 0.43rem;
}

.el-dropdown-link {
  border: 1px solid #dcdfe6;
  padding: 0.43rem 1rem;
  outline: none;
  font-size: 1.16rem;
  color: #999;
}

.cars-subtotal {
  color: #cf4444;
  font-size: 1.33rem;
}

.cars-operation span {
  font-size: 1.16rem;
}

.menu {
  width: 35rem;
  padding: 4.16667rem 1.66667rem 0.83333rem;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 0.83rem;
}

.menu-content {
  display: flex;
  gap: 0.83rem;
  align-items: center;
  flex-wrap: wrap;
}

.menu-item {
  display: flex;
  gap: 0.43rem;
}

.menu-item span {
  display: inline-block;
  padding: 0.43rem 0.66rem;
  box-sizing: border-box;
  font-size: 1.16rem;
  color: #999;
  border: 1px solid #dcdfe6;
}

.menu-item img {
  width: 5rem;
  height: 5rem;
  object-fit: cover;
  border: 1px solid #dcdfe6;
}

.menu-name span {
  color: #999;
  font-size: 1.16rem;
  display: inline-block;
  width: 2.5rem;
}


.menu-bth {
  text-align: center;
  margin-top: 1.66rem;
}

.car-table {
  background-color: #fff;
  padding: 0 1.66rem;
  box-sizing: border-box;
}

.car-table-btn {
  background-color: #fff;
  padding: 3rem 2rem;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-btn {
  display: flex;
  align-items: center;
  gap: 0.83rem;
  font-size: 1.16rem;
}

.right-price {
  color: #cf4444;
  font-size: 1.33rem;
  font-weight: 600;
}

table {
  width: 100%;
  border-collapse: collapse;
}

td {
  border-bottom: 1px solid #f5f5f5;
  padding: 0.83rem 0;
  box-sizing: border-box;
  text-align: left;
  font-size: 1.16rem;
}

th {
  padding: 1.66rem 0;
  box-sizing: border-box;
  font-size: 1.33rem;
  color: #333;
  font-weight: normal;
  text-align: left;
}

thead {
  background-color: #fff;
}

thead th {
  border-bottom: 1px solid #f5f5f5; /* 设置表头上边框颜色 */
}

.commodity-info-img img {
  width: 10rem;
  height: 10rem;
  object-fit: cover;
}

.tb-price {
  color: #cf4444;
}

.tb-delete {
  color: var(--primary-color);
}

.commodity-info-text {
  position: relative;
}

.commodity-info {
  display: flex;
  align-items: center;
  gap: 0.83rem;
}

.commodity-name {
  font-size: 1.33rem;
  color: #333;
  margin-bottom: 0.43rem;
}

.commodity-down span {
  display: inline-block;
  padding: 0.3rem 0.66rem;
  font-size: 1.16rem;
  color: #999;
  border: 1px solid #dcdfe6;
}

.commodity-down-content {
  background-color: #fff;
  border: 1px solid var(--primary-color);
  padding: 0.83rem 1.66667rem 1.66667rem;
  position: absolute;
  width: 33.33rem;
  height: 25.8rem;
  top: 4.5rem;
  left: 0;
  z-index: 100;
}

.commodity-down-item {
  display: flex;
  align-items: center;
}

.commodity-down-item-list {
  display: flex;
  gap: 0.83rem;
  flex-wrap: wrap;
  margin-top: 0.83rem;
}

.commodity-down-name span {
  border: none;
  display: inline-block;
  width: 2.5rem;
}

.cdil-item {
  display: flex;
  gap: 0.43rem;
  flex-wrap: wrap;
  cursor: pointer;
}

.cdil-item span {
  padding: 0.2rem 1.66rem;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
  height: 20.8rem;
  opacity: 1;
}

.slide-fade-leave-active {
  transition: all 0.4s cubic-bezier(1, 0.5, 0.8, 1);
  height: 0;
  opacity: 0;
}

.commodity-down-bth {
  margin-top: 1.66rem;
}

.cdil-item img {
  width: 5rem;
  height: 5rem;
  object-fit: cover;
  border: 1px solid #dcdfe6;
}

.active {
  border: 1px solid var(--primary-color);
}

.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.commodity-down-name-text {
  cursor: pointer;
}

.operation {
  cursor: pointer;
}

.recommend {
  width: 100%;
  margin-top: 1.66rem;
  background-color: #fff;
  padding: 1.66rem 1.66rem;
  box-sizing: border-box;
}

.recommend-content {
  margin-top: 4.16rem;
}

.recommend-title {
  display: flex;
  align-items: center;
  gap: 0.41rem;
}

.recommend-title h2 {
  font-weight: 400;
  font-size: 1.66rem;
}

.recommend-title i {
  color: var(--primary-color);
  font-size: 1.66rem;
}


.recommend-item-image img {
  width: 19.16rem;
  height: 19.16rem;
  object-fit: cover;
}

.recommend-list {
  display: flex;
  justify-content: space-evenly;
}

.recommend-item-info {
  width: 12.5rem;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.recommend-item-info span {
  font-size: 1.16rem;
  color: #666;

}

.recommend-item-info {
  text-align: center;
}

.recommend-item-info span {
  font-size: 1.16rem;
  color: #666;
}

.recommend-item-price span {
  font-size: 1.66rem;
  color: #cf4444;
}
</style>